<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="queryParams.typeName" placeholder="类型名称" clearable @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item label="回收单价（区间）" prop="unitPrice">
          <el-input v-model="queryParams.minUnitPrice" placeholder="最低价（元/吨）" clearable @keyup.enter="handleQuery()"
            style="width: 150px;" />
          <span style="margin: 0 10px;">至</span>
          <el-input v-model="queryParams.maxProcessPrice" placeholder="最高价（元/吨）" clearable @keyup.enter="handleQuery()"
            style="width: 150px;" />
        </el-form-item>
        <el-form-item label="处理单价（区间）" prop="unitPrice">
          <el-input v-model="queryParams.minProcessPrice" placeholder="最低价（元/吨）" clearable @keyup.enter="handleQuery()"
            style="width: 150px;" />
          <span style="margin: 0 10px;">至</span>
          <el-input v-model="queryParams.maxProcessPrice" placeholder="最高价（元/吨）" clearable @keyup.enter="handleQuery()"
            style="width: 150px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['sys:wasteType:add']" type="success" @click="handleOpenDialog()">
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
        <el-button v-hasPerm="['sys:wasteType:delete']" type="danger" :disabled="removeIds.length === 0"
          @click="handleDelete()">
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
      </div>

      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row border
        @selection-change="handleSelectionChange" empty-text="/">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="typeName" label="类型名称" prop="typeName" width="160" align="center" />
        <el-table-column key="marketPrice" label="市场价（元/吨）" prop="marketPrice" width="160" align="center" sortable />
        <el-table-column key="unitPrice" label="回收价（元/吨）" prop="unitPrice" width="160" align="center" sortable />
        <el-table-column key="processPrice" label="处理价（元/吨）" prop="processPrice" width="160" align="center" sortable />
        <el-table-column key="govSubsidyPrice" label="政府补贴（元/吨）" prop="govSubsidyPrice" width="170" align="center"
          sortable />
        <el-table-column key="cercSubsidyPrice" label="碳减排补贴（元/吨）" prop="cercSubsidyPrice" width="180" align="center"
          sortable />
        <el-table-column key="cerc" label="碳减排系数(tCO₂e/t)" prop="cerc" width="200" align="center" sortable />
        <el-table-column key="userRatio" label="用户分成" prop="userRatio" width="150" align="center" sortable />
        <el-table-column key="orgRatio" label="机构分成" prop="orgRatio" width="150" align="center" sortable />
        <el-table-column key="envRating" label="环保评级" prop="envRating" width="150" align="center" sortable />
        <el-table-column key="pointsPerKg" label="积分" prop="pointsPerKg" width="150" align="center" sortable />
        <el-table-column key="description" label="分类标准说明" prop="description" width="200" align="center" />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button v-hasPerm="['sys:wasteType:edit']" type="primary" size="small" link
              @click="handleOpenDialog(scope.row.id)">
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button v-hasPerm="['sys:wasteType:delete']" type="danger" size="small" link
              @click="handleDelete(scope.row.id)">
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery()" />
    </el-card>

    <!-- 垃圾类型管理表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" @close="handleCloseDialog" align-center>
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px" style="padding:10px">
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="formData.typeName" placeholder="类型名称" />
        </el-form-item>

        <el-form-item label="市场价" prop="marketPrice">
          <el-input v-model="formData.marketPrice" placeholder="市场价（元/吨）">
            <template #suffix>
              <span>元/吨</span>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="回收价" prop="unitPrice">
          <el-input v-model="formData.unitPrice" placeholder="回收价（元/吨）">
            <template #suffix>
              <span>元/吨</span>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="处理价" prop="processPrice">
          <el-input v-model="formData.processPrice" placeholder="处理价（元/吨）">
            <template #suffix>
              <span>元/吨</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="政府补贴" prop="govSubsidyPrice">
          <el-input v-model="formData.govSubsidyPrice" placeholder="政府补贴（元/吨）" :disabled="!hasGovPrice" clearable>
            <template #suffix>
              <span>元/吨</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="碳减排补贴" prop="cercSubsidyPrice">
          <el-input v-model="formData.cercSubsidyPrice" placeholder="碳减排补贴（元/吨）">
            <template #suffix>
              <span>元/吨</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="碳减排系数" prop="cerc">
          <el-input v-model="formData.cerc" placeholder="碳减排系数(tCO₂e/t)">
            <template #suffix>
              <span>tCO₂e/t</span>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="用户分成" prop="userRatio">
          <el-input v-model="formData.userRatio" placeholder="请输入用户分成"></el-input>
        </el-form-item>
        <el-form-item label="机构分成" prop="orgRatio">
          <el-input v-model="formData.orgRatio" placeholder="请输入机构分成"></el-input>
        </el-form-item>
        <el-form-item label="环保评级" prop="envRating">
          <el-select v-model="formData.envRating" placeholder="请选择环保评级">
            <el-option v-for="item in envRatings" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="积分" prop="pointsPerKg">
          <el-input v-model.number="formData.pointsPerKg"></el-input>
        </el-form-item>
        <el-form-item label="分类标准说明" prop="description">
          <el-input v-model="formData.description" placeholder="分类标准说明" type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }" resize="none" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div style="text-align:center">
          <el-button @click="handleCloseDialog()">取消</el-button>
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "WasteType",
  inheritAttrs: false,
});

import WasteTypeAPI, { WasteTypePageVO, WasteTypeForm, WasteTypePageQuery, envRatings } from "@/api/system/waste-type";

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<WasteTypePageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 垃圾类型管理表格数据
const pageData = ref<WasteTypePageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 垃圾类型管理表单数据
const formData = reactive<WasteTypeForm>({
  typeName: '',
  marketPrice: '',
  unitPrice: '',
  processPrice: '',
  govSubsidyPrice: '',
  cercSubsidyPrice: '',
  cerc: '',
  userRatio: '',
  orgRatio: '',
  envRating: '',
  description: '',
  pointsPerKg: ''
});

// 垃圾类型管理表单校验规则
const rules = reactive({
  typeName: [{ required: true, message: '类型名称不能为空', trigger: 'blur' }],
  marketPrice: [
    { required: true, message: '市场价不能为空', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确金额格式' }
  ],
  unitPrice: [
    { required: true, message: '回收价不能为空', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确金额格式' }
  ],
  processPrice: [
    { required: true, message: '处理价不能为空', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确金额格式' }
  ],
  govSubsidyPrice: [
    {
      validator: (_, value, callback) => {
        if (hasGovPrice.value && !value) {
          callback(new Error('政府补贴不能为空'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  userRatio: [
    { required: true, message: '用户分成不能为空', trigger: 'blur' },
    { pattern: /^100$|^\d{1,2}(\.\d{1,2})?$/, message: '请输入0-100之间的数值' }
  ],
  orgRatio: [
    { required: true, message: '机构分成不能为空', trigger: 'blur' },
    { pattern: /^100$|^\d{1,2}(\.\d{1,2})?$/, message: '请输入0-100之间的数值' }
  ],
  envRating: [{ required: true, message: '请选择环保评级', trigger: 'change' }]
});

/** 查询垃圾类型管理 */
function handleQuery() {
  loading.value = true;
  WasteTypeAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data?.list || [];
      total.value = data?.total || 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置垃圾类型管理查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.minUnitPrice = undefined;
  queryParams.maxUnitPrice = undefined;
  queryParams.minProcessPrice = undefined;
  queryParams.maxProcessPrice = undefined;
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开垃圾类型管理弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改垃圾类型管理";
    WasteTypeAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增垃圾类型管理";
  }
}

/** 提交垃圾类型管理表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        WasteTypeAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        WasteTypeAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭垃圾类型管理弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  // 先执行表单重置
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  // 遍历响应式对象属性重置
  Object.keys(formData).forEach(key => {
    if (key !== 'id') {
      formData[key] = '';
    }
  });
  formData.id = undefined;
}

/** 删除垃圾类型管理 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      WasteTypeAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

//政府补贴
const hasGovPrice = computed(() => {
  if (formData.unitPrice && formData.processPrice) {
    return parseFloat(formData.unitPrice) <= parseFloat(formData.processPrice);
  }
});


onMounted(() => {
  handleQuery();
});
</script>
